<template>
  <div>
    <Form class="ivu-mb-16">
      <Button
        type="primary"
        @click="handleAdd"
        v-hasC="{
          name: 'v1-base-ad-pic-update-ad-pic',
          flag: 'v1/base/ad-pic/update-ad-pic',
        }"
        >新增</Button
      >
    </Form>
    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      :border="true"
      v-hasC="{ name: 'v1-base-ad-pic-index', flag: 'v1/base/ad-pic/index' }"
    >
      <template #image="{ row }">
        <img
          :src="row.path"
          @click="callClick(row)"
          style="object-fit: contain; width: 80px; height: 40px"
        />
      </template>
      <template #status="{ row }">
        <Badge v-if="+row.status === 1" status="success" text="正常" />
        <Badge v-if="+row.status === 0" status="error" text="停用" />
      </template>
      <template #action="{ row }">
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-base-ad-pic-update-ad-pic2',
            flag: 'v1/base/ad-pic/update-ad-pic',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-base-ad-pic-delete-ad-pic',
            flag: 'v1/base/ad-pic/delete-ad-pic',
          }"
        ></Divider>
        <a
          @click="handleDelete(row)"
          class="delete"
          v-hasC="{
            name: 'v1-base-ad-pic-delete-ad-pic',
            flag: 'v1/base/ad-pic/delete-ad-pic',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      show-total
      show-elevator
      show-sizer
      :total="total"
      :current.sync="params.page"
      :page-size="params.pageSize"
      @on-change="changepage"
      @on-page-size-change="changepageSize"
      v-hasC="{ name: 'v1-base-ad-pic-index', flag: 'v1/base/ad-pic/index' }"
    ></Page>
    <Modal
      :title="add ? '广告图-新增' : '广告图-编辑'"
      width="960"
      v-model="modal"
      :mask-closable="false"
      :draggable="true"
      @on-visible-change="$refs.formvid.resetFields()"
    >
      <Form :label-width="118" ref="formvid" :model="formData" :rules="rules">
        <FormItem label="标题名称" prop="name">
          <Input v-model="formData.name" placeholder="广告图标题名称" />
        </FormItem>
        <FormItem label="缩略图" prop="path" :rules="rules.path">
          <div class="imageUpdate">
            <Upload
              v-model="formData.path"
              :show-upload-list="false"
              :format="['jpg', 'png', 'gif', 'jpeg', 'webp']"
              :action="requestAction"
              :before-upload="beforeUpLoad"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
            >
              <Button
                :loading="uplodloading"
                type="primary"
                class="ivu-ml-8 ivu-mr-8"
              >
                {{ uplodloading ? "上传中..." : "上传" }}
              </Button>
            </Upload>
            <Button type="success" @click="showImgModel = true">选择</Button>
          </div>
        </FormItem>
        <FormItem label="">
          <img
            v-if="modalimgUrl !== ''"
            :src="modalimgUrl"
            width="100"
            height="100"
            style="object-fit: contain"
          />
          <Icon
            v-if="modalimgUrl !== ''"
            type="ios-trash"
            :size="32"
            @click="modalDel"
            style="cursor: pointer"
          />
        </FormItem>
        <FormItem label="文章ID" prop="arc_id">
          <InputNumber
            :precision="0"
            v-width="118"
            placeholder="请输入文章ID"
            v-model="formData.arc_id"
          />
        </FormItem>
        <FormItem label="有效期" prop="validity">
          <RadioGroup v-model="formData.validity">
            <Radio :label="0">长期</Radio>
            <Radio :label="1">临时</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem v-if="formData.validity === 1" label="日期段选择" prop="date">
          <DatePicker type="daterange" :options="options1" v-model="formData.date" />
        </FormItem>
        <FormItem label="排序" prop="sort">
          <InputNumber :precision="0" v-model="formData.sort" :min="1" />
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch v-model="formData.status" />
        </FormItem>
      </Form>
      <template #footer>
        <Button @click="handleCancel">取消</Button>
        <Button type="primary" @click="handleSave" :loading="modalLoading"
          >确定</Button
        >
      </template>
    </Modal>
    <Modal v-model="imgModal" footer-hide>
      <p slot="header">查看大图</p>
      <img :src="imgUrl" style="width: 100%; object-fit: cover" />
    </Modal>
    <glo-check v-model="showImgModel" @getImgArr="getImgArr" />
  </div>
</template>
<script>
import { adpicIndex, updateadPic, deleteadPic } from '@/api/set'
import { updatefileTemp } from '@/api/set.js'
import dayjs from 'dayjs'
import Setting from '@/setting'
import util from '@/libs/util'

export default {
  name: 'modalName',
  data () {
    return {
      showImgModel: false,
      token: util.cookies.get('token'),
      baseUrl: Setting.request.apiBaseURL,
      add: true,
      modal: false,
      modalimgUrl: '',
      total: 0,
      requestAction: '',
      params: { page: 1, pageSize: 10 },
      formData: {
        id: '',
        name: '',
        status: true,
        sort: null,
        validity: 0,
        date: [],
        path: ''
      },
      loading: false,
      columns: [
        {
          title: "id",
          key: 'id',
          width: 60,
          fixed: 'left'
        },
        {
          title: "名称",
          key: 'name',
          width: 118,
          fixed: 'left'
        },
        {
          title: "图片",
          slot: 'image',
          width: 118
        },
        {
          title: "链接内容标题",
          key: 'title',
          minWidth: 168,
          tooltip: true
        },
        {
          title: "有效期",
          key: 'valid_time',
          width: 198
        },
        {
          title: "排序",
          key: 'sort',
          width: 118,
          sortable: true
        },
        {
          title: "状态",
          slot: 'status',
          width: 100
        },
        {
          title: "创建时间",
          key: 'created_at',
          width: 158
        },
        {
          title: "操作",
          slot: 'action',
          width: 118,
          fixed: 'right'
        }
      ],
      rules: {
        name: [
          { required: true, message: '请输入广告图标题名称', trigger: 'bulr' }
        ],
        path: [
          { required: true, message: '请选择图片', trigger: 'bulr,change' }
        ]
      },
      list: [],
      modalLoading: false,
      imgUrl: '',
      imgModal: false,
      uplodloading: false,
      options1: {
          disabledDate (date) {
              return date && date.valueOf() < Date.now() - 86400000;
          }
      }
    }
  },
  mounted () {
    // console.log( Setting.request.apiBaseURL,'Setting.apiBaseURL')
    this.requestAction = this.baseUrl + `/v1/upload/images?auth_access_token=${util.cookies.get('token')}&auth_project_id=${localStorage.getItem('currentProject')}`
  },
  methods: {
    initial () {
      this.getData()
    },
    changepage (index) {
      this.params.page = index
      this.getData()
    },
    changepageSize (val) {
      this.params.pageSize = val
      this.getData()
    },
    getData () {
      this.loading = true
      const params = {
        page: this.params.page,
        pageSize: this.params.pageSize
      }
      adpicIndex(params).then(res => {
        this.list = res.list
        this.total = res.total
      }).finally(() => {
        this.loading = false
      })
    },
    callClick (row) {
      this.imgModal = true
      this.imgUrl = row.path
    },
    handleAdd () {
      this.add = true
      this.modal = true
      this.modalimgUrl = ''
      this.formData.path = ''
    },
    handleEdit (row) {
      this.add = false
      this.formData = {
        id: row.id,
        name: row.name,
        status: +row.status === 1 ? true : false,
        sort: row.sort * 1,
        validity: row.start_time == '' ? 0 : 1,
        date: [row.start_time, row.end_time],
        path: row.path,
        arc_id:row.arc_id

      }
      this.modalimgUrl = `${row.path}`
      this.modal = true
    },
    handleCancel () {
      this.modal = false
      this.modalLoading = false
      this.$refs.formvid.resetFields()
      this.modalimgUrl = ''
    },
    getImgArr (arr) {
      this.modalimgUrl = arr[0]
      this.formData.path = arr[0]
    },
    handleSave () {
      this.$refs.formvid.validate((valid) => {
        if (valid) {
          this.modalLoading = true
          // console.log(this.formData.validity==0?0:this.formData.date[0]?dayjs(this.formData.date[0]).format('YYYY-MM-DD'):'','params')
          const params = {
            name: this.formData.name,
            path: this.formData.path,
            arc_id: this.formData.arc_id,
            start_time: this.formData.validity == 0 ? 0 : this.formData.date[0] ? dayjs(this.formData.date[0]).format('YYYY-MM-DD') : '',
            end_time: this.formData.validity == 0 ? 0 : this.formData.date[1] ? dayjs(this.formData.date[1]).format('YYYY-MM-DD') : '',
            sort: this.formData.sort,
            status: this.formData.status === true ? 1 : 0
          }
          if (this.add) {
            updateadPic(params).then(res => {
              this.$Message.success('新增成功')
              this.handleCancel()
              this.getData()
            }).catch(() => {
              this.modalLoading = false
            })
          } else {
            updateadPic(Object.assign({}, params, { id: this.formData.id })).then(res => {
              this.$Message.success('编辑成功')
              this.handleCancel()
              this.getData()
            }).catch(() => {
              this.modalLoading = false
            })
          }

        }
      })
    },
    handleDelete (row) {
      this.$Modal.confirm({
        title: '温馨提示',
        content: '确定删除此项?',
        onOk: () => {
          deleteadPic({ id: row.id }).then(res => {
            this.$Message.success('删除成功！')
            this.getData()
          })

        }
      })
    },
    modalDel () {
      this.modalimgUrl = ''
      this.formData.path = ''
    },
    //上传前
    beforeUpLoad (file) {
      if ((file.type !== 'image/png') && (file.type !== 'image/jpeg') && (file.type !== 'image/jpg')) {
        this.$Message.error({
          content: '请上传 jpg/jpeg 或 png 格式的图片',
          duration: 5,
          closable: true
        })
        return false
      }
      this.formData.path = ''
      this.modalimgUrl = ''
      this.uplodloading = true
    },
    handleUploadSuccess (response) {
      this.uplodloading = false
      this.formData.path = response.data.image_url[0]
      this.modalimgUrl = `${response.data.host}${response.data.image_url[0]}`
      const id = response.data.image_id[0]
      updatefileTemp({ id })
    },
    handleUploadError (error, file, fileList) {
      this.uplodloading = false
      this.$Message.error(error)
    },
  },
};
</script>
<style lang='less' scoped>
.imageUpdate {
  display: flex;
}
.delete {
  color: rgb(226, 5, 5);
}
</style>